package com.google.code.mochaccino.framework.transaction.provider;

/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import bitronix.tm.resource.jdbc.PoolingDataSource;
import com.google.code.mochaccino.framework.transaction.jsr250.BitronixDataSourceWrapper;
import com.google.common.base.Preconditions;
import java.sql.Driver;
import java.util.Properties;
import javax.sql.DataSource;

/** A XADataSource Provider Implementation for a Last-Commit-Resource. */
public final class XADataSourceProviderLCR extends XAResourceProvider<PoolingDataSource,DataSource>{

	private Class<? extends Driver> driverClass = null;
	private String                  jdbcUrl     = null;
	private String                  password    = null;
	private String                  username    = null;

	public XADataSourceProviderLCR( String uniqueName, String username, String password, Class<? extends Driver> driverClass, String jdbcUrl ) {
		super( Preconditions.checkNotNull( uniqueName ) );
		this.username = Preconditions.checkNotNull( username );
		this.password = Preconditions.checkNotNull( password );
		this.driverClass = Preconditions.checkNotNull( driverClass );
		this.jdbcUrl = Preconditions.checkNotNull( jdbcUrl );
	}

	@Override
	protected PoolingDataSource createUnconfiguredResource() {
		return new PoolingDataSource();
	}

	@Override
	public DataSource get() {
		PoolingDataSource bean = super.createConfiguredResource();
		bean.setClassName( bitronix.tm.resource.jdbc.lrc.LrcXADataSource.class.getName() );
		Properties driverProperties = new Properties();
		driverProperties.setProperty( "user", username );
		driverProperties.setProperty( "password", password );
		driverProperties.setProperty( "driverClassName", driverClass.getName() );
		driverProperties.setProperty( "url", jdbcUrl );
		bean.setDriverProperties( driverProperties );
		return new BitronixDataSourceWrapper( bean );
	}
}
